package com.thinkTank.oa.configuration;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import com.thinkTank.oa.common.UserInfo;
import com.thinkTank.oa.entity.LoginInfomation;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.service.LoginInfomationService;
import com.thinkTank.oa.service.UserService;
import com.thinkTank.oa.util.StrUtil;



@WebFilter(urlPatterns = {"/person/*","/project/*","/customer/*","/demand/*","/conference/*","/"},filterName = "loginFilter")
public class LoginFilter implements Filter{

	
	private LoginInfomationService loginInfomationService;
	
	private UserService userService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	WebApplicationContext context = (WebApplicationContext) filterConfig.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);  
    	loginInfomationService=	(LoginInfomationService)context.getBean("loginInfomationService");
    	userService =(UserService)context.getBean("userService");
    	System.out.println("1111111111111111");
    }
	
    @Override
	public void doFilter(ServletRequest req, ServletResponse resp, javax.servlet.FilterChain chain)
			throws IOException, ServletException {		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse respons = (HttpServletResponse) resp;  
		HttpSession session = request.getSession();
		UserInfo userInfo =(UserInfo)session.getAttribute("userInfo");
		System.out.println("------------------------"+isRememberMeAuthenticated());
		String path = request.getContextPath();  
		if(userInfo==null&&isRememberMeAuthenticated()){
			//自动登录需要写日志，然后跳转到首页
			try{
				UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
						.getPrincipal();
				User user = userService.getUserByUsername(userDetails.getUsername());
				LoginInfomation loginInfo = new LoginInfomation();
				loginInfo.setUserId(user.getPid());
				loginInfo.setLogindate(StrUtil.getCurrentDateTime_two());
				String ip = request.getHeader("x-forwarded-for");
				if(ip == null || ip.startsWith("196.168")||ip.equals("")){
				   ip = request.getRemoteAddr();
				}
				loginInfo.setIp(ip);
				loginInfo.setRemark1("自动登录");
				loginInfomationService.add(loginInfo);
			}catch(Exception e){
				e.printStackTrace();
			}
			String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;  
			respons.sendRedirect(basePath);
		}
		chain.doFilter(req, resp);
	}

    @Override
    public void destroy() {

    }
    private boolean isRememberMeAuthenticated() {

        Authentication authentication = SecurityContextHolder.getContext()
               .getAuthentication();
        if (authentication == null) {
           return false;
       }

       return RememberMeAuthenticationToken.class
               .isAssignableFrom(authentication.getClass());
   }
	
}